﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using enc = KC.Business.Text.Encoding;
using BLL = KC.Business.Web.MV8;
using DAL = KC.DataAccess.MV;

public partial class Blog : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		PopulateTopPosts();

	}
	private void PopulateTopPosts()
	{
		int ItemsPerPage = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ItemsPerPage"]),
			Page = 0,
			TotalPosts = BLL.GetPostCount(),
			lastPage = (int)((double)TotalPosts / (double)ItemsPerPage);
		if (Request.QueryString["Page"] != null)
			int.TryParse(Request.QueryString["Page"], out Page);

		rPosts.DataSource = Page == 0 
			? BLL.GetTopPosts(ItemsPerPage)
			: BLL.GetTopPosts(ItemsPerPage, Page * ItemsPerPage);
		rPosts.DataBind();

		// Update page navigation
		lblPageNo.Text = (Page + 1).ToString() + " of " + (lastPage + 1).ToString();
		hlNewer.Enabled = Page > 0;
		hlOlder.Enabled = Page < lastPage;
		hlOlder.NavigateUrl = "Blog.aspx?Page=" + (Page + 1).ToString();
		hlNewer.NavigateUrl = Page > 1
			? "Blog.aspx?Page=" + (Page - 1).ToString()
			: "Blog.aspx";

	}

	protected void rPosts_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		if (e.Item == null || e.Item.DataItem == null) return;
		DAL.Post p = (DAL.Post)e.Item.DataItem;
		string url = "http://www.kconnolly.net/Post.aspx?" + (string.IsNullOrEmpty(p.FriendlyName) ? "ID=" + p.ID.ToString() : "Title=" + p.FriendlyName);

		HyperLink hlTitle = (HyperLink)e.Item.FindControl("hlTitle");
		hlTitle.Text = p.Title;
		hlTitle.NavigateUrl = url;
		hlTitle.ToolTip =
			p.Title + "\n" +
			"Posted " + p.Created.ToString("MM/dd/yy HH:mm:ss") + " MT \n" +
			"Post Id " + p.ID.ToString();
		hlTitle.Attributes.Remove("rel");
		hlTitle.Attributes.Add("rel", "canonical");

		((Label)e.Item.FindControl("lblBody")).Text = enc.BlogDecodeForRendering(p.Body);
		((Label)e.Item.FindControl("lblDate")).Text = p.Created.ToString("MM/dd/yyyy HH:mm:ss") + " MT";

		//System.Web.UI.HtmlControls.HtmlGenericControl fbIframe = (System.Web.UI.HtmlControls.HtmlGenericControl)e.Item.FindControl("fbIframe");
		((Label)e.Item.FindControl("lblFacebook")).Text =
			"<iframe src=\"http://www.facebook.com/plugins/like.php?href=" + url +
			"&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=80\" " +
			"scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:450px; height:80px;\"></iframe>";
	}

}